import React, {useEffect, useRef, useState, useImperativeHandle} from 'react'
import {Button, Form, message, Card, Steps, Row, Col, Radio, Input} from 'antd'
import {connect, history, useDispatch} from 'umi'
import moment from 'moment'

import RewardInfo from '../components/RewardInfo'
import Basics from '../components/Basics'
import {
	addSaveReward,
	getInitFormDetail,
	getInitFormDetailShop,
	updateSaveReward,
	auditLogging,
	processAudit,
} from '@/service/carRewardRule/rewardRule'
import {getOperatingRecord} from '@/service/marketing/commodity'

import 'moment/locale/zh-cn'
import AssociatedTable from '../components/AssociatedTable'
import {leaseType, subsidyType} from '../constant'
import {getCityIdName, getProvinceIdName} from '@/utils/common/cityIdFilter'
import CustomTable from '@/components/Table'
import styles from './index.less'
import {GlobalState} from '@/models/global'
import Examine from '@/components/Examine'
import {processRecordSave} from '@/service/common/index'

const {TextArea} = Input
interface props {
	global: GlobalState
	location: any
	driverRewardRules: any
	queryType: any
	cRef: any
}

function Add({
	global: {currentRoute},
	location,
	queryType,
	driverRewardRules,
	cRef,
}: props) {
	const routerQuery = queryType || location?.query

	const {pageType, type} = routerQuery

	const [loading] = useState(false)
	const [expire, setIsExpire] = useState<boolean>(false)
	const [basicsForm] = Form.useForm()
	const childRef = useRef<any>(null)
	const dispatch = useDispatch()
	const code = {
		companyData: driverRewardRules?.companyData,
		_companyData: driverRewardRules?._companyData,
		cityData: driverRewardRules?.cityData,
		carTypeList: driverRewardRules?.carTypeList,
		MainCompany: driverRewardRules?.MainCompany,
	}
	// 审核数据定义
	const [stepCurrent, setStepCurrent] = useState(0)
	const [logging, setLogging] = useState<any>([])

	// 操作历史
	const [optionSourse, setOptionSourse] = useState<any[]>([])
	const [optionTotal, setOptionTotal] = useState<any>()
	const [optionParams, setOptionParams] = useState({
		current: 1,
		size: 10,
	})
	const [optionLoading, setOptionLoading] = useState(false)
	const [channelTypename, setChannelTypename] = useState('') // 渠道类型名称

	const [auditForm] = Form.useForm()
	const examineRef = useRef<any>(null)
	/**
	 * 初始查询审核记录
	 */
	const initData = () => {
		auditLogging({id: location?.query?.id})
			.then((res) => {
				if (res?.success) {
					const sCurrent = res?.data?.filter(
						(item: any) => item?.nodeType === 1,
					)
					const step = res?.data?.map(
						(item: {
							activityName: string
							assignee: string
							endTime: string
							message: string
						}) => ({
							title: item?.activityName,
							description: (
								<>
									<div style={{margin: '8px 0 8px'}}>
										{item?.assignee}
									</div>
									<div style={{margin: '8px 0 8px'}}>
										{item?.endTime}
									</div>
									<div style={{margin: '0 0 30px'}}>
										{item?.message}
									</div>
								</>
							),
						}),
					)
					setStepCurrent(() => sCurrent.length - 1)
					setLogging(() => step)
				}
			})
			.catch(() => {})
	}
	// 获取操作记录数据
	const onOperatingListFun = (id: any) => {
		setOptionLoading(true)
		getOperatingRecord({businessType: 30, businessId: id}).then(
			(res: any) => {
				if (res?.success) {
					if (res?.success) {
						setOptionSourse(() => res?.data?.records)
						setOptionTotal(() => res?.data?.total)
					}
					setOptionLoading(false)
				}
			},
		)
	}
	useEffect(() => {
		if (pageType === 'detail' || pageType === 'process') {
			initData()
			onOperatingListFun(location?.query?.id)
		}
	}, [location?.query?.id])
	useEffect(() => {
		dispatch({
			type: 'driverRewardRules/getAllCitys',
		})
		dispatch({
			type: 'driverRewardRules/getCompany',
		})
		dispatch({
			type: 'driverRewardRules/getCarTypeList',
		})
		dispatch({
			type: 'driverRewardRules/getMainCompanyList',
		})
	}, [routerQuery?.type, routerQuery?.id])

	// 初始化表单
	const initFormDate = () => {
		getInitFormDetail({id: routerQuery.id})
			.then((res) => {
				if (res?.success) {
					const data = res?.data
					setChannelTypename(data?.channelTypename)
					setIsExpire(
						String(data?.subsidyType)
							.split(',')
							.map((item) => Number(item))
							.includes(3),
					)

					const baseData = {
						id: data?.id,
						rewardId: data?.rewardId,
						rewardName: data?.rewardName,
						subjectName: data?.subjectName,
						subjectId: Number(data?.subjectId),
						leaseTerm: String(data?.leaseTerm)
							.split(',')
							.map((item) => Number(item)),
						leaseType: String(data?.leaseType),
						leaseTypename: data?.leaseTypename,
						channelType: String(data?.channelType),
						startTime: data?.startTime
							? moment(data?.startTime)
							: null,
						endTime: data?.endTime ? moment(data?.endTime) : null,
						renewalDays: data?.renewalDays,
						remarks: data?.remarks,
						orgName: data?.orgName,
						cityId: [data?.provinceId, data?.cityId],
						orgId: data?.orgId,
						subsidyType: String(data?.subsidyType)
							.split(',')
							.map((item) => Number(item)),
						rewardModelList: data?.rewardModelList.map(
							(item: {modelId: any}) => item.modelId,
						),
					}
					basicsForm.setFieldsValue({...baseData})
					dispatch({
						type: 'driverRewardRules/updateState',
						payload: {
							MAXTERM: Math.max(...baseData.leaseTerm),
						},
					})
					dispatch({
						type: 'driverRewardRules/updateState',
						payload: {
							basic: {
								...baseData,
							},
							detailRecord: [...data.rewardInfoList],
						},
					})
				} else {
					message.warning(res?.msg)
				}
			})
			.catch(() => {})
		const params = {
			rewardId: routerQuery?.rewardId,
			current: 1,
			size: 10,
		}
		getInitFormDetailShop(params)
			.then((res) => {
				if (res?.success) {
					const {
						data: {records},
					} = res
					dispatch({
						type: 'driverRewardRules/updateState',
						payload: {
							outTableList: [...records],
						},
					})
				} else {
					message.warning(res?.msg)
				}
			})
			.catch(() => {})
	}

	useEffect(() => {
		if (
			pageType === 'edit' ||
			pageType === 'detail' ||
			pageType === 'process'
		) {
			initFormDate()
		}
	}, [routerQuery?.id])

	useEffect(() => {
		const ruleParamsPlan = driverRewardRules?.ruleParamsPlan
		if (routerQuery?.type === '1') {
			basicsForm.setFieldsValue({
				...ruleParamsPlan,
				subjectId: Number(ruleParamsPlan?.subjectId),
				cityId: ruleParamsPlan?.city,
				orgId: ruleParamsPlan?.affiliatedCompanyId,
				cityName: ruleParamsPlan?.cityName,
				orgName: ruleParamsPlan?.orgName,
				rewardModelList: [Number(ruleParamsPlan?.brandId)],
				leaseType: ruleParamsPlan?.rentTypeId,
				startTime: moment(ruleParamsPlan?.beginTime),
				endTime: moment(ruleParamsPlan?.endTime),
				leaseTerm: ruleParamsPlan?.leaseTerm,
				subjectName: ruleParamsPlan?.subjectName,
				provinceName: ruleParamsPlan?.provinceName,
			})
			dispatch({
				type: 'driverRewardRules/updateState',
				payload: {
					MAXTERM: ruleParamsPlan?.leaseTerm,
				},
			})
		}
	}, [routerQuery?.type])

	const onSave = async (callback?: any) => {
		const basicsData = await basicsForm.validateFields()
		console.log(basicsData, 'basicsData----')
		const rewardCommodityList = driverRewardRules?.outTableList || []
		const rewardModelList = driverRewardRules?.carTypeList
			.map((obj: {id: any; fullName: any}) => ({
				modelId: obj.id,
				modelName: obj.fullName,
			}))
			.filter((item: {modelId: any}) =>
				basicsData?.rewardModelList?.includes(item.modelId),
			)
		childRef.current.allFormData((rewardInfoList: any) => {
			if (routerQuery?.type === '1' || rewardCommodityList.length) {
				if (rewardInfoList.length) {
					const city = basicsData?.cityId
					const params = {
						...{
							...basicsData,
							channelTypename,
							renewalMark:
								type === '1' ? routerQuery.onlyCode : null,
							leaseTerm: basicsData?.leaseTerm.toString(),
							subsidyType: basicsData?.subsidyType.toString(),
							startTime: basicsData?.startTime
								? moment(basicsData?.startTime).format(
										'YYYY-MM-DD HH:00:00',
								  )
								: null,
							endTime: basicsData?.endTime
								? moment(basicsData?.endTime).format(
										'YYYY-MM-DD HH:00:00',
								  )
								: null,
							subjectName: code.MainCompany.find(
								(item: {id: any}) =>
									item.id === basicsData?.subjectId,
							)?.name,
							leaseTypename: leaseType.find(
								(item) =>
									item.value ===
									Number(basicsData?.leaseType),
							)?.label,
							subsidyTypename: subsidyType
								.filter((item) =>
									basicsData?.subsidyType?.includes(
										item.value,
									),
								)
								.map((lab) => lab.label)
								.join(),
							orgName: code._companyData.find(
								(item: {id: any}) =>
									item.id === Number(basicsData?.orgId),
							)?.name,
							cityName: getCityIdName(code?.cityData, city)?.name,
							cityId: city[1],
							provinceId: city[0],
							provinceName: getProvinceIdName(
								code?.cityData,
								city,
							)?.name,
						},
						rewardInfoList: rewardInfoList?.map((item: any) => {
							const newItem = item
							return {
								...newItem,
								conformance: newItem?.conformance?.toString(),
								security: newItem?.security?.toString(),
								transportCapacity: [
									newItem?.transportCapacity_1,
									newItem?.transportCapacity_2,
									newItem?.transportCapacity_3,
									newItem?.transportCapacity_4,
									newItem?.transportCapacity_5,
									newItem?.transportCapacity_6,
								]
									.filter((i: any) => i)
									?.toString(),
							}
						}),
						rewardModelList,
						rewardCommodityList,
					}
					if (pageType === 'add') {
						// 处理新增的逻辑
						// 新增逻辑
						addSaveReward(params)
							.then((res: any) => {
								if (res?.success) {
									message.success(res?.msg)
									if (type !== '1') {
										dispatch({
											type: 'global/deleteTabs',
											payload: currentRoute,
										})
										history.push({
											pathname:
												'/merchantCenter/driverRewardRules/list',
										})
									} else {
										callback(true)
									}
									dispatch({
										type: 'driverRewardRules/updateState',
										payload: {
											outTableList: [],
										},
									})
								}
							})
							.catch(() => {})
					} else if (pageType === 'edit') {
						// 编辑逻辑
						updateSaveReward({
							id: routerQuery?.id,
							...params,
						})
							.then((res: any) => {
								if (res?.success) {
									message.success(res?.msg)
									dispatch({
										type: 'global/deleteTabs',
										payload: currentRoute,
									})
									history.push({
										pathname:
											'/merchantCenter/driverRewardRules/list',
									})
									dispatch({
										type: 'driverRewardRules/updateState',
										payload: {
											outTableList: [],
										},
									})
								}
							})
							.catch(() => {})
					}
				} else {
					message.error('至少添加一条奖励信息数据！')
				}
			} else {
				message.error('至少添加一条关联商品方案信息数据！')
			}
		})
	}
	const optionColumns: any = [
		{
			title: '操作人',
			dataIndex: 'logPersonname',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},
		{
			title: '操作内容',
			dataIndex: 'logRemark',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},
		{
			title: '操作时间',
			dataIndex: 'logTime',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},
	]
	useImperativeHandle(cRef, () => ({
		// changeVal 就是暴露给父组件的方法
		onSubmit: (e: any) => {
			onSave(e)
		},
	}))
	/**
	 * 提交审核意见
	 */
	const onSubmit = () => {
		const valueForm = auditForm.getFieldsValue()
		const params = {
			ids: [location?.query?.id],
			pass: valueForm.pass,
			message: valueForm.message,
		}
		if (valueForm.pass === 2) {
			processRecordSave({
				bizType: 7,
				bizNo: routerQuery?.id,
				processId: routerQuery.processId,
			})
		}
		processAudit(params)
			.then((res) => {
				if (res?.success) {
					message.success(res?.msg)
					dispatch({
						type: 'global/deleteTabs',
						payload: currentRoute,
					})
					history.push({
						pathname: '/merchantCenter/driverRewardRules/list',
					})
				}
			})
			.catch(() => {})
	}
	return (
		<div className={styles.add}>
			{routerQuery.processId ? (
				<Card id="审批记录" title="审批记录" bordered={false}>
					<Examine
						ref={examineRef}
						examineType={false}
						orgId={routerQuery.orgId}
						processInstanceId={routerQuery.processId}
						bizType={7}
						bizNo={routerQuery.id}
					/>
				</Card>
			) : (
				<></>
			)}
			{pageType === 'process' ? (
				<div className="process">
					<Steps progressDot current={stepCurrent} items={logging} />
					<div className="processTitle">
						<div className="title">审核</div>
					</div>
					<Form
						form={auditForm}
						className="toExamineForm"
						name="basic"
						layout="horizontal"
						labelCol={{flex: '100px'}}
						labelAlign="right"
						labelWrap
						initialValues={{remember: true}}
						autoComplete="off">
						<Row gutter={12}>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="审核状态"
									name="pass"
									rules={[
										{
											required: true,
											message: '请选择审核状态',
										},
									]}>
									<Radio.Group>
										<Radio value={1}>审核通过</Radio>
										<Radio value={2}>审核驳回</Radio>
									</Radio.Group>
								</Form.Item>
							</Col>
							<Col span={24} />
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item label="处理意见" name="message">
									<TextArea
										maxLength={200}
										placeholder="请填写处理意见，不超过200个字符"
										autoSize={{
											minRows: 3,
											maxRows: 6,
										}}
									/>
								</Form.Item>
							</Col>
						</Row>
					</Form>
				</div>
			) : null}
			<Basics
				pageType={pageType}
				basicsForm={basicsForm}
				routerQuery={routerQuery}
				code={code}
				expire={expire}
				callBack={() => childRef.current.clearCostitemList()}
				setChannelTypename={setChannelTypename}
			/>
			<RewardInfo
				routerQuery={routerQuery}
				cRef={childRef}
				driverRewardRules={driverRewardRules}
			/>
			{routerQuery?.type !== '1' ? (
				<AssociatedTable routerQuery={routerQuery} />
			) : null}
			{/* {pageType === 'detail' ? (
				<Card
					id="审批信息"
					title="审批信息"
					bordered={false}
					className="info">
					<Steps
						progressDot
						current={stepCurrent}
						items={logging}
						className="process"
					/>
				</Card>
			) : (
				<></>
			)} */}

			{pageType === 'detail' ? (
				<Card id="操作记录" title="操作记录" bordered={false}>
					<CustomTable
						params={optionParams}
						columns={optionColumns}
						pagination
						total={optionTotal}
						scroll={{y: 500}}
						callback={(pagination: any) => {
							setOptionParams(pagination)
						}}
						kid="id"
						loading={optionLoading}
						dataSource={optionSourse}
					/>
				</Card>
			) : (
				<></>
			)}
			{routerQuery?.type !== '1' ? (
				<div className={styles.operation}>
					<Button
						style={{marginLeft: 5}}
						onClick={() => {
							dispatch({
								type: 'global/deleteTabs',
								payload: currentRoute,
							})
							history.push({
								pathname:
									'/merchantCenter/driverRewardRules/list',
							})
						}}>
						取消
					</Button>
					{pageType === 'process' ? (
						<Button type="primary" onClick={() => onSubmit()}>
							提交
						</Button>
					) : null}
					{pageType === 'add' || pageType === 'edit' ? (
						<Button
							type="primary"
							loading={loading}
							onClick={() => {
								onSave()
							}}>
							提交
						</Button>
					) : null}
				</div>
			) : null}
		</div>
	)
}
export default connect(({driverRewardRules, global, user}: any) => ({
	user,
	global,
	driverRewardRules,
}))(Add)
